const App = getApp()
const db = wx.cloud.database()
const _ = db.command
const remind = require('../../../common/remind/remind.js')
// 监听器
let watcher
let that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    // 发起考勤弹窗
    show: false,
    // 时间弹窗
    timeshow: false,
    // 考勤历史详情弹窗
    hisShow: false,
    // 时间默认值和最大最小时间
    currentDate: '00:05',
    minHour: 0,
    maxHour: 24,
    // 时间格式
    formatter(type, value) {
      if (type === 'hour') {
        return `${value}时`;
      }
      if (type === 'minute') {
        return `${value}分`;
      }
      return value;
    },
    // 折叠
    activeNames: ['1'],
    // 课程id
    courseId: "",
    // 课程详情数组
    courselist: [],
    // 倒计时
    timeData: {},
    // 正在考勤的数据
    codelist: "",
    // 获取考勤记录
    codelistHistory: [],
    // 考勤记录详情对象
    HisDetails: "",
    // 签到码输入框
    CheckinCode: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this
    let courseId = JSON.parse(decodeURIComponent(options.passData));
    console.log('拿到传值回来的课程id:', courseId);
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    that.setData({
        courseId,
        UserInfo
      }),
      // 获取课程详情
      that.getcourse()
    // 获取正在考勤的数据
    // that.getAttendance()
    // 监听器
    App.toast.showLoading('加载中')
    watcher = db.collection('attendance-record')
      .where(_.and([{
          courseId: _.eq(courseId)
        },
        {
          attendanceSwitch: _.eq(true)
        }
      ])).watch({
        onChange: this.onChange.bind(this),
        onError: function (err) {
          console.error(err)
          App.toast.hideLoading()
        }

      })

  },
  // 监听器
  onChange(snapshot) {
    console.log('is init data', snapshot.type === 'init')
    console.log(snapshot);
    if (snapshot.type === 'init') {
      console.log('snapshot', snapshot);
      let list = snapshot.docs[0]
      console.log('list', list);
      if (!list) {
        console.log('没有正在考勤');
        return false
      }
      list.time = list.time - Date.now()
      console.log('获取正在考勤的数据', list);
      list.Member.sort((x, y) => y.SigninNum - x.SigninNum)
      that.setData({
        codelist: list
      })
    } else {
      console.log('更新snapshot', snapshot);
      for (const docChange of snapshot.docChanges) {
        // queueTyoe: 列表更新类型，表示更新事件对监听列表的影响
        switch (docChange.queueType) {
          case 'update':
            let list = docChange.doc
            list.time = list.time - Date.now()
            list.Member.sort((x, y) => y.SigninNum - x.SigninNum)
            that.setData({
              codelist: list
            })
            break
          case 'enqueue':
            let addlist = docChange.doc
            addlist.time = addlist.time - Date.now()
            addlist.Member.sort((x, y) => y.SigninNum - x.SigninNum)
            that.setData({
              codelist: addlist
            })
            break
        }
      }


    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    watcher.close()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // tabs切换
  ontabsChange(event) {
    that.getAttendanceHis()
  },
  // 签到码输入
  handleChange(e) {
    console.log(e.detail.value);
    this.setData({
      CheckinCode: e.detail.value
    })
  },
  // 打开考勤弹窗
  showPopup() {
    this.setData({
      show: true
    });
  },
  // 关闭考勤弹窗
  onClose() {
    this.setData({
      show: false
    });
  },
  // 打开考勤历史详情弹窗
  showHisPopup(e) {
    let key = e.currentTarget.dataset.attendancekey
    // 传值考勤的id给考勤历史记录详情方法
    that.getAttendanceHisDetails(key)
    this.setData({
      hisShow: true
    });
  },
  // 关闭考勤历史详情弹窗
  onHisClose() {
    this.setData({
      hisShow: false
    });
  },
  // 打开时间弹窗
  showTimePopup() {
    this.setData({
      timeshow: true
    });
  },
  // 关闭时间弹窗
  onTimeClose() {
    this.setData({
      timeshow: false,
    });
  },
  // 确认选择时间
  confirmTime(event) {
    console.log('确认了', event.detail);
    this.setData({
      timeshow: false,
      currentDate: event.detail,
    });
  },
  // 时间变化
  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },
  // 自定义倒计时
  onChangetime(e) {
    this.setData({
      timeData: e.detail,
    });
  },
  // 复制签到码
  codekey(e) {
    console.log(e.currentTarget.dataset.attendancekey);
    wx.setClipboardData({
      data: e.currentTarget.dataset.attendancekey,
      success: res => {
        App.toast.showToast('签到码已复制', 'none', 1000)
      }
    })
  },
  // 获取课程详情
  getcourse() {
    App.toast.showLoading('加载中')
    db.collection('course').where({
        courseId: that.data.courseId
      })
      .get({
        success: function (res) {
          let courselist = res.data[0]
          console.log('获取该课程', courselist)
          that.setData({
            courselist: courselist,
          })
          App.toast.hideLoading()
        }
      })
    App.toast.hideLoading()

  },
  // 创建考勤
  addAttendance() {
    // 获取截至时间,单位是秒
    let timeinput = that.data.currentDate
    let hours = parseFloat(timeinput.substring(0, 2))
    let minutes = parseInt(timeinput.substring(3, 5))
    let times = (hours * 60 * 60) + (minutes * 60)
    if (times == 0) {
      App.toast.showToast('不能低于一分钟')
      return false
    }
    // 把秒转成时间戳
    times = (times * 1000) + Date.now()
    console.log('提交的时间', App.Time.formatTime(times));
    App.toast.showLoading('创建中')
    // 获取课程详情数组
    let courselist = that.data.courselist
    // 将老师自己从考勤成员中去除
    let Member = courselist.courseMember.filter(item => {
      return item.account != that.data.UserInfo.account
    })
    // 给每个成员加上考勤字段
    Member.forEach(item => {
      // 默认缺勤字段
      item.Signin = false,
        item.SigninNum = 2
    })
    console.log('Member', Member);
    db.collection('attendance-record').add({
        data: {
          time: times,
          Member: Member,
          coursename: courselist.coursename,
          courseId: courselist.courseId,
          initiator: {
            account: that.data.UserInfo.account,
            name: that.data.UserInfo.nickName
          },
          timeTs: Date.now(),
          attendanceKey: (+new Date()).toString().substring(5, 13),
          attendanceSwitch: true,
          permissions: true
        }
      })
      .then(res => {
        console.log(res, '创建成功');
        // 将考勤上传到消息中心,
        // 第一项 是消息类别，比如上课提醒、实践任务提醒、系统信息
        //  第二项 是接收信息的成员数组 
        //  第三项 是发布的提醒内容 （有默认项，可不填）
        remind.Message('SystemMsg', Member, '你所参与的' + courselist.coursename + '课程发起了考勤，请赶快查看。')
        App.toast.hideLoading()
        // that.getAttendance()
        // 关闭考勤弹窗
        that.onClose()
      })

  },


  // 获取考勤记录
  getAttendanceHis() {
    App.toast.showLoading('加载中')
    db.collection('attendance-record').where(_.and([{
          courseId: _.eq(that.data.courseId)
        },
        {
          attendanceSwitch: false
        }
      ]))
      .get({
        success: function (res) {
          console.log('考勤记录', res.data)
          // 判断用户是否已经签到过
          let list = res.data
          // 给当前用户是否考勤的状态加到考勤记录数组里，方便判断
          list.forEach(x => {
            for (let i = 0; i < x.Member.length; i++) {
              let item = x.Member[i]
              if (item.account == that.data.UserInfo.account) {
                x.temporary = item.Signin
              }
            }
          })
          // 根据创建时间排序
          list.sort((s, y) => y.timeTs - s.timeTs)
          console.log('list', list);
          App.toast.hideLoading()
          that.setData({
            codelistHistory: list
          })
        }
      })
  },
  // 获取考勤历史记录详情
  getAttendanceHisDetails(e) {
    console.log('拿到记录key', e);
    let key = e
    let codelistHis = that.data.codelistHistory
    let HisDetails = codelistHis.filter(item => {
      return item.attendanceKey == key
    })
    // 得到详情对象
    console.log('HisDetails', HisDetails);
    // 根据签到状态排序
    HisDetails[0].Member.sort((s, y) => y.SigninNum - s.SigninNum)
    that.setData({
      HisDetails: HisDetails[0]
    })
  },
  // 倒计时结束后关闭考勤
  closeAttendance() {
    db.collection('attendance-record').where(_.and([{
        courseId: _.eq(that.data.courseId)
      },
      {
        attendanceSwitch: true
      }
    ])).update({
      data: {
        attendanceSwitch: false
      },
      success: function (res) {
        console.log(res.data, '考勤已经关闭')
        App.toast.showToast('考勤已经关闭')
        that.setData({
          codelist: ''
        })
      }
    })
  },
  // 提交签到码
  submit() {
    let CheckinCode = that.data.CheckinCode
    if (CheckinCode == '') {
      App.toast.showToast('签到码不能为空', "error")
      return false
    }
    App.toast.showLoading('验证中')
    db.collection('attendance-record').where(_.and([{
          courseId: _.eq(that.data.courseId)
        },
        {
          attendanceSwitch: true
        },
        {
          'Member.account': _.eq(that.data.UserInfo.account)
        }
      ]))
      .get({
        success: function (res) {
          App.toast.hideLoading()
          console.log('有吗', res.data[0])
          let list = res.data[0]
          // 判断用户是否已经签到过
          let judge = list.Member.some(x => {
            return x.account == that.data.UserInfo.account && x.Signin == true
          })
          if (judge == true) {
            App.toast.showToast('不可以重复签到')
            return false
          }
          if (list.attendanceKey == CheckinCode) {
            db.collection('attendance-record').where(_.and([{
                _id: list._id
              },
              {
                Member: {
                  account: _.eq(that.data.UserInfo.account)
                }
              }
            ])).update({
              data: {
                'Member.$.Signin': true,
                'Member.$.SigninNum': 1,
              },
              success: function (res) {
                console.log(res)
                App.toast.showToast('签到成功', "success")
                that.setData({
                  CheckinCode: ""
                })
              }
            })
          } else {
            App.toast.showToast('签到码不对！', "error")
            that.setData({
              CheckinCode: ""
            })
          }
        }
      })
  },
  // 提前终止
  termination() {
    wx.showModal({
      title: '提示',
      content: '是否提前终止',
      success(res) {
        if (res.confirm) {
          db.collection('attendance-record').where(_.and([{
              courseId: _.eq(that.data.courseId)
            },
            {
              attendanceSwitch: true
            }
          ])).update({
            data: {
              attendanceSwitch: false,
              termination: true,
              endTime: Date.now(),
            },
            success: function (res) {
              console.log(res.data, '考勤已经关闭')
              App.toast.showToast('考勤已经关闭')
              that.setData({
                codelist: ''
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }
})